#include "stdafx.h"
#include "BasicReaderWriter.h"
#include <atlpath.h>

using namespace Rendering;
using namespace concurrency;

vector<byte> BasicReaderWriter::ReadData(string filename)
{
	CAtlString fName(filename.data());
	CPath path;
	path.Combine(_T("D:\\development\\Planogram\\src\\Planogram\\bin\\Debug"), fName);

	HANDLE file = CreateFile(path.m_strPath,                // name of the file to read
                       GENERIC_READ,          // open for reading
                       FILE_SHARE_READ,                      // do not share
                       nullptr,                   // default security
                       OPEN_EXISTING,             // create new file only
                       FILE_ATTRIBUTE_NORMAL,  // normal file
                       nullptr); 


    if (file == INVALID_HANDLE_VALUE)
    {
		throw 0;
    }

    BY_HANDLE_FILE_INFORMATION fileInfo = {0};
    if (!GetFileInformationByHandle(file, &fileInfo))
		throw 0;

	__int64 size = ( ((__int64)fileInfo.nFileSizeHigh) << 32 ) + fileInfo.nFileSizeLow;
    vector<byte> fileData(static_cast<long>(size));

    if(!ReadFile(
        file,
		fileData.data(),
        static_cast<long>(size),
        nullptr,
        nullptr
        ))
		throw 0;

    return fileData;
}

task<vector<byte>> BasicReaderWriter::ReadDataAsync(_In_ string filename)
{
	return task<vector<byte>>([=](){return ReadData(filename); });
}

UINT BasicReaderWriter::WriteData(
    _In_ string filename,
    _In_ const vector<byte> fileData
    )
{
	CAtlString fName(filename.data());
    HANDLE file = CreateFile(fName,
            GENERIC_WRITE,
            0,
			nullptr,
            CREATE_ALWAYS,
			FILE_ATTRIBUTE_NORMAL,
			nullptr
            );
    
	if (file == INVALID_HANDLE_VALUE)
    {
		throw 0;
    }

    DWORD numBytesWritten = 0;
    if(!WriteFile(
            file,
			fileData.data(),
            fileData.size(),
            &numBytesWritten,
            nullptr
            ))
			throw 0;

    if(numBytesWritten != fileData.size())
		throw 0;

    return numBytesWritten;
}

task<void> BasicReaderWriter::WriteDataAsync(
    _In_ string filename,
    _In_ const vector<byte> fileData
    )
{
	return task<void>([=]()
	{
		WriteData(filename, fileData);
	});
}